﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using CMN.Controllers.Filters;
using CMN.Framework;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Sys_RolePermissionController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        /// <summary>
        /// 返回角色应用权限表列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            //返回json数组
            int roleId=Utils.StringToInt(actionId,0);
            if (!UserData.CheckUserIsManagerRole(roleId))
            {
                return returnJson = "{success:'false',message:'没有权限修改角色" + roleId.ToString() + "'}";
            }
            QueryParam qp = new QueryParam();
            qp.PageIndex = 1;
            qp.PageSize = Int32.MaxValue;
            int recordNum = 0;
            
            IDataService<Sys_ModuleExtPermissionEntity> sys_ModuleExtPermissionSv = ServiceBuilder.BuildSys_ModuleExtPermissionService();
           
            qp.PageIndex=1;
            qp.PageSize=Int32.MaxValue;
            IDataService<Sys_ModuleEntity> sys_ModuleEntitySv = ServiceBuilder.BuildSys_ModuleService();
            IDataService<Sys_RolePermissionEntity> sys_RolePermissionSv=ServiceBuilder.BuildSys_RolePermissionService();

            List<Sys_ModuleEntity> sys_ModuleEntityList=sys_ModuleEntitySv.List(qp,out recordNum);

            List<Sys_ModuleEntity> sys_ModuleEntityTemp = new List<Sys_ModuleEntity>();
            //父级名称
            for (int i = 0; i < sys_ModuleEntityList.Count; i++)
            {
                for (int j = 0; j < sys_ModuleEntityList.Count; j++)
                {
                    if (sys_ModuleEntityList[i].M_ParentID == sys_ModuleEntityList[j].ModuleID)
                    {
                        sys_ModuleEntityList[i].M_ParentName = sys_ModuleEntityList[j].M_CName;
                        break;
                    }
                }
            }
            sys_ModuleEntityTemp.Clear();

            qp.Orderfld="";
            List<Sys_ModuleExtPermissionEntity> sys_ModuleExtPermissionList = sys_ModuleExtPermissionSv.List(qp,out recordNum);
            List<Sys_PermissionItem> permissionList = new List<Sys_PermissionItem>();
            qp.Orderfld="";
            qp.Where= string.Concat(" P_RoleID=",roleId.ToString()," and P_Value>0");
            List<Sys_RolePermissionEntity> sys_RolePermissionList = sys_RolePermissionSv.List(qp, out recordNum);

            //移除权限
            for (int i = 0; i < sys_ModuleEntityList.Count; i++)
            {
                if (sys_ModuleEntityList[i].M_ParentID == 0)
                {
                    //sys_ModuleEntityList.Remove(sys_ModuleEntityList[i]);
                }
                else
                {
                    if (UserData.CheckPageCode(UserData.GetUserData.UserID, sys_ModuleEntityList[i].M_PageCode))
                    {
                            sys_ModuleEntityTemp.Add(sys_ModuleEntityList[i]);
                    }
                }
               
            }


            foreach (Sys_ModuleEntity sysModule in sys_ModuleEntityTemp)
            {

                permissionList = GetPermissionList(sysModule, sys_ModuleExtPermissionList);
                sysModule.M_Icon = FormatPermission(permissionList, sysModule.M_PageCode, GetPermissionValue(sysModule.M_PageCode, sys_RolePermissionList));

            }
            returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(sys_ModuleEntityTemp), "}");
            return returnJson;
        }

        /// <summary>
        /// 获取module权限值
        /// </summary>
        /// <param name="pageCode"></param>
        /// <param name="sys_RolePermissionList"></param>
        /// <returns></returns>
        public int GetPermissionValue(string pageCode, List<Sys_RolePermissionEntity> sys_RolePermissionList)
        {
            int returnInt = 0;
            foreach (Sys_RolePermissionEntity permission in sys_RolePermissionList)
            {
                if (permission.P_PageCode == pageCode)
                {
                    returnInt = permission.P_Value;
                    break;
                }
            }
            return returnInt;
        }


        /// <summary>
        /// 获得模块的权限集合
        /// </summary>
        /// <param name="moduleID">模块ID</param>
        /// <returns>返回模块权限列表</returns>
        public List<Sys_PermissionItem> GetPermissionList(Sys_ModuleEntity module, List<Sys_ModuleExtPermissionEntity> extPermissionlst)
        {
            List<Sys_PermissionItem> lst = new List<Sys_PermissionItem>();
            PermissionManger.GetDefaultPermissionItem(lst);
            List<Sys_PermissionItem> rlst = new List<Sys_PermissionItem>();
            for (int i = 0; i < lst.Count; i++)
            {
                if (UserData.CheckPageCode(UserData.GetUserData.UserID, module.M_PageCode, lst[i].PermissionValue))
                {
                    rlst.Add(lst[i]);
                }
            }
            foreach (Sys_ModuleExtPermissionEntity var in extPermissionlst)
            {
                if (var.ModuleID ==module.ModuleID)
                {
                    rlst.Add(new Sys_PermissionItem(var.PermissionName, var.PermissionValue, var.PermissionCode, false));
                }
            }
            return rlst;
        }

        /// <summary>
        /// 获得权限显示文本
        /// </summary>
        /// <param name="pagecode">模块Pagecode</param>
        /// <param name="permissionName">权限名称</param>
        /// <param name="permissionValue">权限值</param>
        /// <param name="allow">是否允许</param>
        /// <returns>显示文本</returns>
        public string FormatPermission(List<Sys_PermissionItem> lst, string pagecode, int userpermissionValue)
        {
            string rightString = "";
            string SelectTxt = "";
            foreach (Sys_PermissionItem var in lst)
            {
                SelectTxt = "";
                var.Allow = (userpermissionValue & var.PermissionValue) == var.PermissionValue;
                bool isallow = var.Allow;
                //判断当前角色所属用户是否享有当前权限
                //if (!UserData.CheckPageCode(GetRoleUserID, ApplicationID, pagecode, var.PermissionValue))
                //{
                //    DisableCheckbox = "disabled";
                //}
                //else
                //{
                //    DisableCheckbox = "";
                //}
                if (var.Allow)
                {
                    SelectTxt = "checked";
                }
                else
                {
                    SelectTxt = "";
                }
                rightString += string.Format("<input type=\'checkbox\' value=\'{0}|{3}\' {2} />{1}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", var.PermissonCode, var.PermissionName, SelectTxt,var.PermissionValue);

            }
            return rightString;
        }

        /// <summary>
        /// 查看角色应用权限表 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Sys_RolePermissionEntity> Sys_RolePermissionSv = ServiceBuilder.BuildSys_RolePermissionService();
            int intId=Utils.StringToInt(actionId,0);
            Sys_RolePermissionEntity sys_rolepermission = Sys_RolePermissionSv.Look(intId);
            if (sys_rolepermission != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(sys_rolepermission), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

       

        /// <summary>
        /// 更新角色应用权限表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            
            int ExtPermissionID = Utils.StringToInt(actionId,0);
            if (!UserData.CheckUserIsManagerRole(ExtPermissionID))
            {
                return returnJson = "{success:'false',message:'没有权限修改角色" + ExtPermissionID .ToString()+ "'}";
            }
            string code= (String)Utils.GetQueryAndFormString("Code", this,Int32.MaxValue, 1, DataType.Str);
            List<string> stringListPermmsiion = Utils.StringToArray(code, ';', false);
            int PValue = 0;
            string[] PValues;
            Sys_RolePermissionEntity sys_rolepermission = new Sys_RolePermissionEntity();
            IDataService<Sys_RolePermissionEntity> Sys_RolePermissionSv = ServiceBuilder.BuildSys_RolePermissionService();
            try
            {
                for (int i = 0; i < stringListPermmsiion.Count; i++)
                {
                   
                    PValues = Utils.SplitString(stringListPermmsiion[i], ":");
                    PValue = Utils.StringToInt(PValues[1], 0);

                    if (UserData.CheckPageCode(UserData.GetUserData.UserID, PValues[0]))
                    {
                        sys_rolepermission.P_PageCode = PValues[0];
                        sys_rolepermission.P_RoleID = ExtPermissionID;
                        sys_rolepermission.P_Value = PValue;
                        Sys_RolePermissionSv.Update(sys_rolepermission);
                    }
                }

                returnJson = "{success:'true'}";
            }
            catch (Exception ex)
            {
                returnJson = "{success:'false',message:'" + Utils.UrlDecode( ex.Message.Replace("'", "")) + "'}";
            }
           

            return returnJson;
        }

        /// <summary>
        /// 新增角色应用权限表
        /// </summary>
        /// <returns>json</returns>
        public string Insert()
        {
           // Sys_RolePermissionEntity sys_rolepermission = new Sys_RolePermissionEntity();
           // sys_rolepermission.DataTable_Action = DataTableAction.Insert;
           // sys_rolepermission.P_RoleID = (Int32)Utils.GetQueryAndFormString("P_RoleID", this, 10,  1 , DataType.Int);
           // sys_rolepermission.P_PageCode = (String)Utils.GetQueryAndFormString("P_PageCode", this, 20,  1 , DataType.Str);
           // sys_rolepermission.P_Value = (Int32)Utils.GetQueryAndFormString("P_Value", this, 10,  0, DataType.Int);
           //IDataService<Sys_RolePermissionEntity> Sys_RolePermissionSv = ServiceBuilder.BuildSys_RolePermissionService();
           // if (Sys_RolePermissionSv.Insert(sys_rolepermission))
           // {
           //     returnJson = "{success:'true'}";
           // }
           // else
           //     returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 删除角色应用权限表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Sys_RolePermissionEntity sys_rolepermission = new Sys_RolePermissionEntity();
                sys_rolepermission.PermissionID = intId;
                IDataService<Sys_RolePermissionEntity> Sys_RolePermissionSv = ServiceBuilder.BuildSys_RolePermissionService();
                if (Sys_RolePermissionSv.Delete(sys_rolepermission) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除角色应用权限表
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Sys_RolePermissionEntity> Sys_RolePermissionSv = ServiceBuilder.BuildSys_RolePermissionService();
                if (Sys_RolePermissionSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
